<template>
  <div class="particle-fluid-login-wrap" ref="loginWrap">
    <!-- 粒子流体画布 -->
    <canvas ref="fluidCanvas" class="fluid-canvas"></canvas>

    <div class="login-container">
      <div class="login-panel">
        <div class="panel-header">
          <div class="logo-section">
            <div class="fluid-logo">
              <svg viewBox="0 0 200 200" class="logo-svg">
                <defs>
                  <linearGradient id="logoGradient" x1="0%" y1="0%" x2="100%" y2="100%">
                    <stop offset="0%" style="stop-color:#667eea;stop-opacity:1" />
                    <stop offset="100%" style="stop-color:#764ba2;stop-opacity:1" />
                  </linearGradient>
                  <filter id="glow">
                    <feGaussianBlur stdDeviation="4" result="coloredBlur"/>
                    <feMerge>
                      <feMergeNode in="coloredBlur"/>
                      <feMergeNode in="SourceGraphic"/>
                    </feMerge>
                  </filter>
                </defs>
                <circle cx="100" cy="100" r="80" fill="url(#logoGradient)" filter="url(#glow)"/>
                <circle cx="100" cy="100" r="60" fill="none" stroke="#fff" stroke-width="2" opacity="0.5"/>
                <circle cx="100" cy="100" r="40" fill="none" stroke="#fff" stroke-width="2" opacity="0.3"/>
              </svg>
            </div>
            <h2 class="fluid-title">ERP管理系统</h2>
            <p class="fluid-subtitle">流体粒子登录</p>
          </div>
        </div>

        <el-form
          ref="loginFormRef"
          :model="loginForm"
          :rules="loginRules"
          class="login-form"
          @submit.prevent="handleLogin"
        >
          <el-form-item prop="username">
            <div class="input-wrapper">
              <el-input
                v-model="loginForm.username"
                placeholder="请输入用户名"
                size="large"
                prefix-icon="User"
                class="fluid-input"
              />
              <div class="input-border"></div>
            </div>
          </el-form-item>

          <el-form-item prop="password">
            <div class="input-wrapper">
              <el-input
                v-model="loginForm.password"
                type="password"
                placeholder="请输入密码"
                size="large"
                prefix-icon="Lock"
                class="fluid-input"
                show-password
              />
              <div class="input-border"></div>
            </div>
          </el-form-item>

          <el-form-item>
            <div class="remember-forgot">
              <el-checkbox v-model="rememberMe" class="fluid-checkbox">
                <span>记住我</span>
              </el-checkbox>
              <a class="fluid-link" @click="forgotPassword">忘记密码？</a>
            </div>
          </el-form-item>

          <el-form-item>
            <el-button
              type="primary"
              size="large"
              class="fluid-button"
              :loading="loading"
              @click="handleLogin"
            >
              <span>登录</span>
            </el-button>
          </el-form-item>
        </el-form>

        <div class="panel-footer">
          <p class="footer-text">
            还没有账号？
            <a class="fluid-link" @click="register">立即注册</a>
          </p>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, onUnmounted, nextTick } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'

const router = useRouter()
const store = useUserStore()

const emit = defineEmits(['login'])

const loginWrap = ref(null)
const fluidCanvas = ref(null)
const loginFormRef = ref(null)
const loading = ref(false)
const rememberMe = ref(false)

const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码长度不能少于6位', trigger: 'blur' }
  ]
}

const handleLogin = async () => {
  if (!loginFormRef.value) return

  try {
    await loginFormRef.value.validate()
    loading.value = true

    const response = await store.login(loginForm)

    if (response.code === 200) {
      ElMessage.success(response.msg || '登录成功')
      emit('login', response)
      router.push('/dashboard')
    } else {
      ElMessage.error(response.msg || '登录失败')
    }
  } catch (error) {
    console.error('登录失败:', error)
    ElMessage.error(error.message || '网络请求失败，请重试')
  } finally {
    loading.value = false
  }
}

const register = () => {
  ElMessage.info('注册功能开发中...')
}

const forgotPassword = () => {
  ElMessage.info('忘记密码功能开发中...')
}

let animationId = null
let particles = []
let mouse = { x: 0, y: 0 }

class Particle {
  constructor(x, y) {
    this.x = x
    this.y = y
    this.size = Math.random() * 3 + 1
    this.speedX = Math.random() * 2 - 1
    this.speedY = Math.random() * 2 - 1
    this.color = `hsl(${Math.random() * 60 + 200}, 70%, 60%)`
  }

  update() {
    this.x += this.speedX
    this.y += this.speedY

    if (this.x < 0 || this.x > window.innerWidth) this.speedX *= -1
    if (this.y < 0 || this.y > window.innerHeight) this.speedY *= -1
  }

  draw(ctx) {
    const gradient = ctx.createRadialGradient(
      this.x, this.y, 0,
      this.x, this.y, this.size * 10
    )
    gradient.addColorStop(0, this.color)
    gradient.addColorStop(1, 'transparent')

    ctx.fillStyle = gradient
    ctx.beginPath()
    ctx.arc(this.x, this.y, this.size * 10, 0, Math.PI * 2)
    ctx.fill()
  }
}

const initParticles = () => {
  const canvas = fluidCanvas.value
  if (!canvas) return

  const ctx = canvas.getContext('2d')
  canvas.width = window.innerWidth
  canvas.height = window.innerHeight

  particles = []
  const particleCount = Math.floor((canvas.width * canvas.height) / 15000)

  for (let i = 0; i < particleCount; i++) {
    particles.push(
      new Particle(
        Math.random() * canvas.width,
        Math.random() * canvas.height
      )
    )
  }
}

const animate = () => {
  const canvas = fluidCanvas.value
  if (!canvas) return

  const ctx = canvas.getContext('2d')
  ctx.clearRect(0, 0, canvas.width, canvas.height)

  particles.forEach(particle => {
    particle.update()
    particle.draw(ctx)
  })

  drawConnections(ctx)

  animationId = requestAnimationFrame(animate)
}

const drawConnections = (ctx) => {
  for (let i = 0; i < particles.length; i++) {
    for (let j = i + 1; j < particles.length; j++) {
      const dx = particles[i].x - particles[j].x
      const dy = particles[i].y - particles[j].y
      const distance = Math.sqrt(dx * dx + dy * dy)
      const maxDistance = 150

      if (distance < maxDistance) {
        ctx.strokeStyle = `rgba(${135 + Math.random() * 50}, ${206 + Math.random() * 30}, ${250 - Math.random() * 50}, ${1 - distance / maxDistance})`
        ctx.lineWidth = 0.5
        ctx.beginPath()
        ctx.moveTo(particles[i].x, particles[i].y)
        ctx.lineTo(particles[j].x, particles[j].y)
        ctx.stroke()
      }
    }
  }
}

const handleMouseMove = (e) => {
  mouse.x = e.x
  mouse.y = e.y

  // 吸引附近的粒子
  particles.forEach(particle => {
    const dx = mouse.x - particle.x
    const dy = mouse.y - particle.y
    const distance = Math.sqrt(dx * dx + dy * dy)
    const maxDistance = 100

    if (distance < maxDistance) {
      const force = (maxDistance - distance) / maxDistance
      particle.speedX += (dx / distance) * force * 0.1
      particle.speedY += (dy / distance) * force * 0.1
    }
  })
}

const handleResize = () => {
  initParticles()
}

onMounted(async () => {
  await nextTick()
  initParticles()
  animate()
  window.addEventListener('resize', handleResize)
  if (loginWrap.value) {
    loginWrap.value.addEventListener('mousemove', handleMouseMove)
  }
})

onUnmounted(() => {
  if (animationId) {
    cancelAnimationFrame(animationId)
  }
  window.removeEventListener('resize', handleResize)
  if (loginWrap.value) {
    loginWrap.value.removeEventListener('mousemove', handleMouseMove)
  }
})
</script>

<style scoped>
.particle-fluid-login-wrap {
  position: relative;
  width: 100vw;
  height: 100vh;
  overflow: hidden;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.fluid-canvas {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: 1;
}

.login-container {
  position: relative;
  width: 100%;
  height: 100%;
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 10;
}

.login-panel {
  position: relative;
  width: 450px;
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(20px);
  border: 1px solid rgba(255, 255, 255, 0.3);
  border-radius: 20px;
  padding: 50px 40px;
  box-shadow: 
    0 8px 32px rgba(0, 0, 0, 0.1),
    inset 0 1px 0 rgba(255, 255, 255, 0.2);
}

.panel-header {
  text-align: center;
  margin-bottom: 40px;
}

.logo-section {
  position: relative;
}

.fluid-logo {
  width: 100px;
  height: 100px;
  margin: 0 auto 20px;
  animation: logoFloat 6s ease-in-out infinite;
}

.logo-svg {
  width: 100%;
  height: 100%;
  filter: drop-shadow(0 0 20px rgba(255, 255, 255, 0.5));
}

@keyframes logoFloat {
  0%, 100% { transform: translateY(0) rotate(0deg); }
  50% { transform: translateY(-10px) rotate(5deg); }
}

.fluid-title {
  font-size: 32px;
  font-weight: bold;
  color: white;
  margin: 0 0 10px;
  text-shadow: 0 2px 10px rgba(0, 0, 0, 0.3);
}

.fluid-subtitle {
  font-size: 14px;
  color: rgba(255, 255, 255, 0.9);
  margin: 0;
  letter-spacing: 2px;
}

.login-form {
  width: 100%;
}

.input-wrapper {
  position: relative;
  margin-bottom: 30px;
}

.fluid-input {
  width: 100%;
}

:deep(.el-input__wrapper) {
  background: rgba(255, 255, 255, 0.2);
  border: 1px solid rgba(255, 255, 255, 0.3);
  box-shadow: none;
  transition: all 0.3s;
  border-radius: 12px;
}

:deep(.el-input__wrapper:hover) {
  background: rgba(255, 255, 255, 0.25);
  border-color: rgba(255, 255, 255, 0.5);
}

:deep(.el-input.is-focus .el-input__wrapper) {
  background: rgba(255, 255, 255, 0.3);
  border-color: rgba(255, 255, 255, 0.8);
  box-shadow: 0 0 20px rgba(255, 255, 255, 0.3);
}

:deep(.el-input__inner) {
  color: white;
}

:deep(.el-input__inner::placeholder) {
  color: rgba(255, 255, 255, 0.6);
}

.input-border {
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%) scaleX(0);
  width: 0;
  height: 2px;
  background: linear-gradient(90deg, transparent, white, transparent);
  transition: width 0.3s;
}

:deep(.el-input.is-focus ~ .input-border) {
  width: 100%;
  transform: translateX(-50%) scaleX(1);
}

.remember-forgot {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.fluid-checkbox :deep(.el-checkbox__label) {
  color: white;
  font-size: 14px;
}

.fluid-checkbox :deep(.el-checkbox__input.is-checked .el-checkbox__inner) {
  background-color: rgba(255, 255, 255, 0.9);
  border-color: rgba(255, 255, 255, 0.9);
}

.fluid-link {
  color: white;
  font-size: 14px;
  cursor: pointer;
  text-decoration: none;
  transition: all 0.3s;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.2);
}

.fluid-link:hover {
  text-shadow: 0 0 10px rgba(255, 255, 255, 0.8);
}

.fluid-button {
  width: 100%;
  height: 50px;
  background: rgba(255, 255, 255, 0.9);
  border: none;
  color: #764ba2;
  font-size: 16px;
  font-weight: bold;
  letter-spacing: 2px;
  border-radius: 12px;
  transition: all 0.3s;
  box-shadow: 0 4px 15px rgba(0, 0, 0, 0.2);
}

.fluid-button:hover {
  background: white;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.3);
  transform: translateY(-2px);
}

:deep(.fluid-button.is-loading) {
  background: rgba(255, 255, 255, 0.7);
}

.panel-footer {
  text-align: center;
  margin-top: 20px;
}

.footer-text {
  color: rgba(255, 255, 255, 0.9);
  font-size: 14px;
}
</style>

